<template>
    <div>
        <a-card>
            <p slot="title">
                VPN基础配置
            </p>
            <div class="syMsg">
                <div class="syMsgTit">控制面板</div>
                <div class="syMsgCot">
                    <a-form ref="form" class="onePageMsg">
                        <a-form-item label="VPN运行状态：" v-bind="formStyle">
                            <span :style="showArrow?'color:#419aff':''">{{showArrow?'运行中':'已停止'}}</span>
                        </a-form-item>
                        <a-form-item  label=" " v-bind="formStyle" class="noLabelAfter" style="width: 900px; margin-left: -30px;">
                            <a-button type="primary" size="default" @click="startDeviceFun('restart')">重启VPN服务</a-button>
                            <a-button type="primary" size="default" @click="startDeviceFun('stop')">停止VPN服务</a-button>
                            <a-button type="primary" size="default" @click="startDeviceFun('start')">启动VPN服务</a-button>
                            <a-button type="primary" size="default" @click="" >客户端密钥同步</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </div>
            <div class="syMsg">
                <div class="syMsgTit">基础参数配置</div>
                <div class="syMsgCot">
                    <a-form ref="form" :form="form" class="onePageMsg">
                        <a-form-item label="VPN部署模式：" v-bind="formStyle">
                            <a-radio-group  v-decorator="['vpnMode', { initialValue: '0' }]" disabled>
                                <a-radio value="0">服务端模式</a-radio>
                                <a-radio value="1">客户端模式</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="本地服务端IP：" v-bind="formStyle" required >
                            <a-select placeholder="全部" v-decorator="['ip']" @change="" style="width: 360px" >
                                <a-select-option v-for="item in vpnAllList.ip" :value="item" :key="item">{{item }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="端口：" v-bind="formStyle" required>
                            <a-input-number
                                            placeholder="请输入端口"
                                            :min="1"
                                            :max="65535"
                                            :formatter="verify.limitInteger"
                                            :parser="verify.limitInteger"
                                            style="width: 360px"
                                            v-decorator="['port', { rules: [{ required: true, message: '请输入1-65535的正整数' }] }]"
                            ></a-input-number>
                        </a-form-item>
                        <template v-if="vpnMode === '0'">
                        <a-form-item label="虚拟IP网段：" v-bind="formStyle" required>
                            <a-input type="text"  style="width: 360px" v-decorator="[
                                        'virtualNet',
                                        {
                                            rules: [{ required: true, message: '请输入合法IP' }, { validator: this.verify.validateIP.bind(this) }],
                                            getValueFromEvent: event => {
                                                return this.verify.formalIP(event,18)
                                            }
                                        }
                                    ]" />
                        </a-form-item>
                        <a-form-item label="子网掩码：" v-bind="formStyle" required>
                            <a-input placeholder="请输入子网掩码" class="formWidth"
                                     v-decorator="[
                        'virtualNetMask',
                        {
                            rules: [
                                { required: true, message: '请输入合法子网掩码' },
                                { validator: this.verify.validatenetmask.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalIP(event,18)
                            }
                        }
                    ]"
                        />
                        </a-form-item>
                            </template>
                        <a-form-item label="通信协议" v-bind="formStyle" required>
                            <a-select  style="width: 360px"  v-decorator="['protocol', { rules: [{ required: true, message: '请选择通信协议' }] }]">
                                <a-select-option v-for="item in vpnAllList.protocol" :value="item" :key="item">{{item }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="隧道类型" v-bind="formStyle" required>
                            <a-select style="width: 360px"  v-decorator="['tunnelType', { rules: [{ required: true, message: '请选择隧道类型' }] }]">
                                <a-select-option v-for="item in vpnAllList.tunnelType" :value="item" :key="item">{{item }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="加密算法" v-bind="formStyle" required>
                            <a-select style="width: 360px"  v-decorator="['encryptionType', { rules: [{ required: true, message: '请选择加密算法' }] }]">
                                <a-select-option v-for="item in vpnAllList.encryptionType" :value="item" :key="item">{{item }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="校验算法" v-bind="formStyle" required>
                            <a-select style="width: 360px"  v-decorator="['hashType', { rules: [{ required: true, message: '请选择校验算法' }] }]">
                               <a-select-option v-for="item in vpnAllList.hashType" :value="item" :key="item">{{item }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label="密钥更新周期：" v-bind="formStyle" required>
                            <a-input-number
                                            placeholder="请输入密钥更新周期"
                                            :min="1"
                                            :max="65535"
                                            :formatter="verify.limitInteger"
                                            :parser="verify.limitInteger"
                                            style="width: 360px"
                                            v-decorator="['keyUpdateCycle', { rules: [{ required: true, message: '请输入1-65535的正整数' }] }]"
                            ></a-input-number>
                        </a-form-item>
                        <a-form-item label="压缩：" v-bind="formStyle" required>
                            <a-switch  style="width: 40px; min-width: 50px!important;" v-model="compress" />
                        </a-form-item>
                        <a-form-item label="AASTU加密：" v-bind="formStyle" required>
                            <a-switch style="width: 40px; min-width: 50px!important;" v-model="qencryption" />
                        </a-form-item>
                        <a-row style="margin-bottom: 24px;" v-if="vpnMode === '0'">
                            <a-col span="4" style="text-align: right; padding-right: 8px;">
                                推送路由
                            </a-col>
                            <a-col span="20" style="position: relative">
                                <a-table :columns="columns" :dataSource="loadData" bordered :rowKey="record => record.id"
                                         :pagination="false" :scroll="{ y: 172 }" class="pushRouteTable">
                                    <span slot="index" slot-scope="text, record, index">
                                        {{ (page.currentPage - 1) * page.pageSize + index + 1 }}
                                    </span>
                                    <span slot="operation" slot-scope="text" class="table-operation">
                                        <a @click="$refs.adRouteEdit.showEdit(text)">编辑</a>
                                        <a @click="removeIp(text)" class="adel">删除</a>
                                    </span>
                                </a-table>
                                <a class="routeAddClass" @click="$refs.adRouteEdit.showAddModal()"><a-icon type="plus" style="color: #fff;" /></a>
                            </a-col>
                        </a-row>
                        <a-form-item  label=" " v-bind="formStyle" class="noLabelAfter">
                            <a-button type="primary" size="default" @click="confirm" >保存</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </div>
        </a-card>
        <ad-route-edit ref="adRouteEdit" @addRouteListFun="addRouteListFun"/>
        <div class="spinBox" v-if="spinning">{{spinText}}</div>
    </div>
</template>

<script>
    import verify from 'libs/verify'
    import adRouteEdit  from './adRouteEdit'
    export default {
        name: 'initSetting',
        components: {
            adRouteEdit
        },
        data () {
            return {
                form: this.$form.createForm (this),
                verify,
                spinning: false,
                compress: false,
                qencryption: false,
                spinText: '请稍后...',
                id:0,
                showArrow:false,
                columns: [
                    {title: '序号', key: 'index', width: '80px',  align: 'center', scopedSlots: {customRender: 'index'}},
                    {title: 'IP', dataIndex: 'targetNet', key: 'targetNet', width: '220px',  scopedSlots: {customRender: 'targetNet'}},
                    {title: '子网掩码', dataIndex: 'targetNetMask', key: 'targetNetMask', width: '220px',  scopedSlots: {customRender: 'targetNetMask'}},
                    {title: '操作', key: 'operation',scopedSlots: {customRender: 'operation'}}
                ],
                loadData:[],
                formStyle: {
                    labelCol: {span: 4},
                    wrapperCol: {span:20}
                },
                netWorkList:[],
                page:{
                    currentPage:1,
                    pageSize:10
                },
                vpnMode:'0',
                vpnAllList:{
                    vpnModes:[],
                    ip:[],
                    protocol:[],
                    tunnelType:[],
                    encryptionType:[],
                    hashType:[],
                },
            }
        },
        created () {
            let _this = this
            this.getVpnValueList ()
            this.init ()
            /*this.loadData = [{id:1,targetNet:'192.0.0.1',targetNetMask:'255.255.255.1'},
                {id:2,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:3,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:4,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:5,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:6,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:7,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:8,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:9,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
                {id:10,targetNet:'192.0.0.2',targetNetMask:'255.255.255.0'},
            ]*/
        },
        methods: {
            addRouteListFun(isEdit,data){
                if(isEdit){
                    let newData = this.loadData
                    let target = newData.filter(item=>item.id === data.id)[0]
                    target.targetNet  = data.targetNet
                    target.targetNetMask  = data.targetNetMask
                }else{
                    data.id = this.loadData.length + 1
                    this.loadData.push(data)
                }

            },
            getVpnValueList(){
                this.$get('/vpn/getBaseConfigValues').then(res => {
                    if (res.code === 0) {
                        this.vpnAllList = res.data
                    } else {
                        this.$message.error(res.message)
                    }
                }).catch(res => {
                    this.$message.error(res.message)
                })
            },
            startDeviceFun(text){
                let self = this
                let url = ''
                let msg = ''
                if(text === 'restart'){
                    url = '/vpn/reboot'
                    msg = '重启'
                }else if(text === 'stop'){
                    url = '/vpn/stop'
                    msg = '关闭'
                }else if(text === 'start'){
                    url = '/vpn/start'
                    msg = '启动'
                }
                self.$confirm ({
                    title: `是否${msg}VPN服务?`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        self.spinning = true
                        self.$post(url).then (res => {
                            if (res.code === 0) {
                                self.$message.success('${msg}VPN服务命令下发成功，请稍后')
                                setTimeout(()=>{
                                    self.spinning = false
                                    self.init()
                                    /*sessionStorage.clear()
                                    localStorage.setItem ('interceptorMsg','重启成功后，请重新登录')
                                    window.location.reload();*/
                                },1000 * 60)   //重启设备后服务也会重新启动需要等待时间
                            } else {
                                self.spinning = false
                                self.$message.error (res.message)
                            }
                        })
                    }
                })
            },

            /**
             * Function    : formalIP
             * Description : IP过滤器
             * Input       : none
             * Return      : none
             */
            formalIP ( event ) {
                let a = event.target.value
                a = a.replace (/[^\d\.]/g, '')
                return a
            },
            /**
             * Function    : init
             * Description : 初始化VPN基础信息
             * Input       : none
             * Return      : none
             */
            init () {
                let _this = this
                this.$get('/vpn/getBaseConfig').then(res => {
                    if (res.code === 0) {
                        let data = res.data
                        _this.vpnMode = data.vpnMode
                        _this.$nextTick (() => {
                            _this.form.setFieldsValue (_this.$pick (data, [ 'vpnMode', 'ip', 'port', 'protocol', 'tunnelType',
                                'encryptionType', 'hashType', 'compress', 'keyUpdateCycle' , 'qencryption' ]))
                        })
                        this.compress = data.compress === 1
                        this.qencryption = data.qencryption === 1
                        if(_this.vpnMode === '0'){
                            _this.$nextTick (() => {
                                _this.$nextTick (() => {
                                    _this.$nextTick (() => {
                                        _this.form.setFieldsValue (_this.$pick (data, [ 'virtualNet', 'virtualNetMask' ]))
                                    })
                                })
                            })
                            this.loadData = res.data.pushRoutes
                            this.loadData.forEach((item,idx)=>{
                                item.id =  idx + 1
                            })
                        }

                    } else {
                        _this.$message.error(res.message)
                    }
                })
            },

            removeIp(text){
                this.loadData =  this.loadData.filter(item=>item.id !== text.id)
            },

            /**
             * Function    : confirm
             * Description : 表单提交
             * Input       : data
             * Return      : none
             */
            confirm (e) {
                e.preventDefault();
                this.form.validateFields((err, value) => {
                    let _this = this
                    if (!err) {
                        if(_this.vpnMode === '0') {
                            value.pushRoutes = this.loadData
                        }
                        let compressData = 1
                        if(_this.compress === false){
                            compressData = 0
                        }
                        let qencryptionData = 1
                        if(_this.qencryption === false){
                            qencryptionData = 0
                        }
                        value.compress = compressData
                        value.qencryption = qencryptionData
                        _this.$post('/vpn/setBaseConfig',value).then(res => {
                            if (res.code === 0) {
                                _this.$emit('init')
                                _this.$message.success('修改成功');
                            } else {
                                _this.$message.error(res.message)
                            }
                        })
                    }
                })
            },

            /**
             * Function    : clearListTimer
             * Description : 关闭定时器
             * Input       : none
             * Return      : none
             */
            clearListTimer () {
                let _this = this
                if (_this.timer !== null) {
                    clearInterval (_this.timer)
                    _this.timer = null
                }
            }
        },
        destroyed () {
            this.clearListTimer ()
        }
    }
</script>
<style lang="less">
    .routeAddClass{
        position: absolute; right: -205px; top: 0; width: 30px; height: 30px; background: #2cc141; display: inline-block;
        border-radius: 4px; line-height: 30px; text-align: center; font-size: 20px; color: #fff;
    }
    .routeAddClass:hover{
        opacity: 0.8;
    }
</style>
